from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)


class UserManager(BaseUserManager):
    def create_user(self, email, username, fullname, sex, mobile_number,
                    password=None):
        """
        Creates and saves a User with the given email, username, fullname, sex,
        mobile_number, password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(email=self.normalize_email(email),
                          username=username,
                          fullname=fullname,
                          sex=sex,
                          mobile_number=mobile_number)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, fullname, sex, mobile_number,
                         password):
        """
        Creates and saves a superuser with the given email username, fullname,
        sex, mobile_number and password.
        """
        user = self.create_user(email,
                                username,
                                fullname,
                                sex,
                                mobile_number,
                                password=password)
        user.is_admin = True
        user.save(using=self._db)
        return user


class User(AbstractBaseUser):
    SEXES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )

    email = models.EmailField(max_length=255, unique=True)
    username = models.CharField(max_length=64, unique=True)
    fullname = models.CharField(max_length=255)
    sex = models.CharField(max_length=1, choices=SEXES)
    mobile_number = models.CharField(max_length=20, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'fullname', 'sex', 'mobile_number']

    def get_full_name(self):
        # The user is identified by their email address
        return self.fullname

    def get_short_name(self):
        # The user is identified by their email address
        return self.username

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin
